package com.atguigu.gulimall.ware.listener;

import com.atguigu.entity.to.OrderTo;
import com.atguigu.entity.to.mq.StockLockedTo;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    /**
     * 1。库存自动解锁
     * 下单成功，库存锁定成功，业务失败导致订单回滚，之前锁定的库存要自动解锁
     * 2。订单失败
     *
     *         //解锁
     *         //查询数据库关于这个订单的锁定库存信息
     *         //有：库存锁定成功了
     *             //解锁需要查看订单情况
     *             //1.没有这个订单，必须解锁
     *             //2。有这个订单
     *                 //查看订单状态：已取消：需要解锁
     *                 //          没取消：不能解锁
     *         //没有：库存锁定失败，库存回滚了，这种情况无需回滚
     *
     *         //解锁库存消息失败，一定要告诉服务器，需要开启手动模式
     *
     * @param lockedTo
     * @param message
     */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo lockedTo, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存到消息");

        try {
            wareSkuService.unlockStock(lockedTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            //有异常把消息重新放进队列中
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }

    /**
     * 订单关闭时解锁库存
     * @param to
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void handleOrderCloneRelease(OrderTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到订单关闭解锁库存到消息");

        try {
            wareSkuService.unlockStock(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            //有异常把消息重新放进队列中
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }

}
